﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using LibrarySync2.Business.FileSystem.Item;
using LibrarySync2.Common.Xml;
using LibrarySync2.Common.Interfaces;
using LibrarySync2.Common.Extensions;
using System.Xml.Schema;
using System.Xml;
using System.IO;

namespace LibrarySync2.Business.FileSystem
{
    [Serializable]
    public class Blacklist : List<MediaFile>, IXmlSerializable
    {
        internal bool ContainsMediaFile(string mediaFileId)
        {
            if (string.IsNullOrEmpty(mediaFileId))
                throw new ArgumentNullException("mediaFileId");

            return this.FirstOrDefault<MediaFile>(mf => mf.Id.Equals(mediaFileId, StringComparison.OrdinalIgnoreCase)) != null;
        }

        #region IXmlSerializable Members

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            var document = new XmlDocument();
            document.Load(reader);
            ReadElementsFromXml(document.SelectSingleNode("//Blacklist/Children"));
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteStartElement("Children");
            WriteElementsToXml(writer);
            writer.WriteEndElement();
        }

        private void WriteElementsToXml(XmlWriter writer)
        {
            foreach (MediaFile child in this)
            {
                writer.WriteStartElement("Child");
                writer.WriteAttributeString("Type", child.GetType().FullName);
                child.WriteXml(writer);
                writer.WriteEndElement();
            }
        }

        private void ReadElementsFromXml(XmlNode itemNode)
        {
            var childNodes = itemNode.SelectNodes("Child");
            foreach (XmlNode childNode in childNodes)
            {
                var typeString = childNode.GetNodeAttributeValue("Type");
                var childItemXml = childNode.InnerXml;

                var childType = Type.GetType(typeString);
                var childItem = childType.Instantiate<MediaFile>();

                using (var childReader = new XmlTextReader(new StringReader(childItemXml)))
                {
                    childItem.ReadXml(childReader);
                }

                this.Add(childItem);
            }
        }

        #endregion
    }
}
